﻿using System;
using System.Web.UI.WebControls;
using Resources;
using Yglu.BusinessLayer;
using Yglu.BusinessLayer.Entities;
using Yglu.BusinessLayer.Enums;
using Yglu.BusinessLayer.Reports;

namespace Yglu.WebAdmin
{
	public partial class Users_aspx : BasePage
	{
		#region Main methods

		protected void Page_Load(object sender, EventArgs e)
		{
			CheckPermissions(AdminLevel.Store);

			if (!IsPostBack)
			{
				PanEdit.Visible = false;

				SetDefaults();
			}
		}

		protected void Page_PreRender(Object sender, EventArgs e)
		{
			if (PanGrid.Visible)
			{
				LoadData();
			}

			PlaceReports.Visible = PanEdit.Visible && TxtUserId.Text != "0";
		}

		private void SetDefaults()
		{
			SetDefaults(GridUsers);
			SetDefaults(GridReports);

			TxtUserId.Enabled = false;

			if (SessionManager.LoggedUser.AdminLevel >= AdminLevel.Company)
			{
				CboStore.DataSource = Settings.Stores;
				CboStore.DataBind();
			}
			else
			{
				ButAddNew.Visible = false;
				CboStore.Enabled = false;
				CboAdminLevel.Enabled = false;

				CboStore.Items.Add(new ListItem(SessionManager.LoggedStore.Title, SessionManager.LoggedStore.Id.ToString()));
			}
		}

		private void LoadData()
		{
			if (SessionManager.LoggedStore.Id > 0)
			{
				GridUsers.DataSource = new UserCollection(DataAccess.User_Get(SessionManager.LoggedStore));
			}
			else
			{
				GridUsers.DataSource = new UserCollection(DataAccess.User_Get());
			}

			GridUsers.DataBind();

			CboAdminLevel.Items.Add(new ListItem(AdminLevel.NoAdmin.ToString(), ((Int32)AdminLevel.NoAdmin).ToString()));
			CboAdminLevel.Items.Add(new ListItem(AdminLevel.Store.ToString(), ((Int32)AdminLevel.Store).ToString()));
			CboAdminLevel.Items.Add(new ListItem(AdminLevel.Company.ToString(), ((Int32)AdminLevel.Company).ToString()));

			if (SessionManager.LoggedUser.AdminLevel == AdminLevel.All)
			{
				CboAdminLevel.Items.Add(new ListItem(AdminLevel.All.ToString(), ((Int32)AdminLevel.All).ToString()));
			}

			LblGridCount.Text = GetLocalResourceObject("LblGridCount.Text").ToString().Replace("#", GridUsers.Rows.Count.ToString());

			PanEdit.Visible = false;
			PanGrid.Visible = true;
		}

		#endregion

		#region Add and edit

		protected void ButAddNew_Click(Object sender, EventArgs e)
		{
			TxtUserId.Text = "0";
			TxtPassword.Text = String.Empty;
			TxtPasswordConfirm.Text = String.Empty;
			TxtUserFullName.Text = String.Empty;
			TxtUserPhone.Text = String.Empty;
			ChkUserActive.Checked = true;

			LitEditLegend.Text = GetLocalResourceObject("LitAddUser.Text").ToString();
			PanEdit.Visible = true;
			PanGrid.Visible = false;
		}

		protected void GridUsers_RowCommand(Object sender, GridViewCommandEventArgs e)
		{
			EditUser(Convert.ToInt32(e.CommandArgument));
		}

		private void EditUser(Int32 row)
		{
			Int32 id = Convert.ToInt32(GridUsers.Rows[row].Cells[0].Text);
			User u = new User(id);

			TxtUserId.Text = u.Id.ToString();
			CboStore.SelectedValue = u.Store.Id.ToString();
			TxtUserFullName.Text = u.FullName;
			TxtUserPhone.Text = u.Phone;
			CboAdminLevel.SelectedValue = ((Int32)u.AdminLevel).ToString();
			ChkUserActive.Checked = u.Active;

			LitEditLegend.Text = GetLocalResourceObject("LitEditUser.Text").ToString();
			PanEdit.Visible = true;
			PanGrid.Visible = false;

			LoadReports(u);
		}

		private void LoadReports(User u)
		{
			UserOrdersCollection reports = ReportManager.GetUserOrders(u.Id);

			GridReports.DataSource = reports;
			GridReports.DataBind();
		}

		#endregion

		#region Save to database

		protected void ButSave_Click(Object sender, EventArgs e)
		{
			Page.Validate();

			if (!Page.IsValid)
			{
				return;
			}

			User u = new User(Convert.ToInt32(TxtUserId.Text));

			try
			{
				u.Store = new Store(Convert.ToInt32(CboStore.SelectedValue));
				u.FullName = TxtUserFullName.Text.Trim();
				u.Phone = TxtUserPhone.Text.Trim();
				u.AdminLevel = (AdminLevel)Convert.ToInt32(CboAdminLevel.SelectedValue);
				u.Active = ChkUserActive.Checked;

				if (TxtPassword.Text.Length > 3 && TxtPassword.Text == TxtPasswordConfirm.Text)
				{
					u.PasswordHash = BusinessLayer.Entities.User.GetPasswordHash(u.Store.Id, TxtPassword.Text.Trim());
				}

				try
				{
					DataAccess.User_Upsert(u);

					TxtUserId.Text = u.Id.ToString();

					ClientScript.RegisterStartupScript(typeof(String), "UserSaved", "YgluTopAlert('" + Messages.ConfirmationDataSaved + "', true);", true);

					PanGrid.Visible = true;
				}
				catch (Exception ex)
				{
					Master.SetError(ex, Messages.ErrorCouldNotSaveData);
				}
			}
			catch (Exception ex)
			{
				Master.SetError(ex, Messages.ErrorInvalidForm);
			}
		}

		protected void ButCancel_Click(Object sender, EventArgs e)
		{
			PanEdit.Visible = false;
			PanGrid.Visible = true;
		}

		#endregion
	}
}